package pers.xiqingbo.web;

import com.google.code.kaptcha.servlet.KaptchaServlet;
import com.google.gson.Gson;
import pers.xiqingbo.pojo.User;
import pers.xiqingbo.service.UserService;
import pers.xiqingbo.service.impl.UserServiceImpl;
import pers.xiqingbo.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @PackageName: ${PACKAGE_NAME}
 * @ClassName: ${NAME}
 * @Description: 处理用户登录注册表示层
 * @Author: Schieber
 * @Date: 2021/2/18 上午 4:26
 */
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    /**
     * 注册功能
     *
     * @param request  请求
     * @param response 响应
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String mailbox = request.getParameter("mailbox");
        String code = request.getParameter("code");

        User user = WebUtils.copyParamToBean(new User(), request.getParameterMap());

        // 从google kaptcha获取到验证码信息
        String verificationCode = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);

        // 每次获取到验证码信息后就在Session中移除掉该验证码信息，防止第二次重复提交验证码仍然正确
        request.getSession().removeAttribute("verificationCode");

        // 验证码不等于null（在Session中移除验证码后，原验证码会为null，所以需要此判断）
        if (verificationCode != null && verificationCode.equalsIgnoreCase(code)) {
            System.out.println("验证码[" + code + "]正确");
            // 2、调用service
            if (userService.verifyUser(username)) {
                System.out.println("用户名可使用");
                userService.registerUser(new User(null, username, password, mailbox));
                // 3、将数据共享到域
                request.setAttribute("msg", "用户名可使用");
                request.setAttribute("username", username);
                request.setAttribute("mailbox", mailbox);
                // 4、跳转路径
                request.getRequestDispatcher("/pages/user/register_success.jsp").forward(request, response);
            } else {
                System.out.println("用户名已存在");
                // 3、将数据共享到域
                request.setAttribute("msg", "用户名已存在");
                request.setAttribute("username", username);
                request.setAttribute("mailbox", mailbox);
                // 4、跳转路径
                request.getRequestDispatcher("/pages/user/register.jsp").forward(request, response);
            }
        } else {
            System.out.println("验证码[" + code + "]错误");
            // 3、将数据共享到域
            request.setAttribute("msg", "验证码错误");
            request.setAttribute("username", username);
            request.setAttribute("mailbox", mailbox);
            // 4、跳转路径
            request.getRequestDispatcher("/pages/user/register.jsp").forward(request, response);
        }
    }

    /**
     * 注册时使用ajax技术实时验证用户名是否可用
     *
     * @param request  请求
     * @param response 响应
     * @throws ServletException
     * @throws IOException
     */
    protected void ajaxVerifyUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取客户端传递的用户名参数
        String username = request.getParameter("username");

        // 调用UserService验证用户名是否可用
        boolean existsUsername = userService.verifyUser(username);

        // 将返回的结果封装成Map对象
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername", existsUsername);

        Gson gson = new Gson();
        // 调用toJson()将字符串转换为Json形式
        String json = gson.toJson(resultMap);

        response.getWriter().write(json);
    }

    /**
     * 登录功能
     *
     * @param request  请求
     * @param response 响应
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 调用Service
        User user = userService.loginUser(username, password);
        // 将数据共享到域
        request.setAttribute("user", user);
        if (user == null) {
            System.out.println("用户名或密码错误,登录失败");
            // 将数据共享到域
            request.setAttribute("msg", "用户名或密码错误");
            request.setAttribute("username", username);
            // 跳转路径
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
        } else {
            System.out.println("用户名和密码正确,登录成功");
            // 将通过用户名密码查询到的用户保存在Session域中
            request.getSession().setAttribute("user", user);
            // 跳转路径
            request.getRequestDispatcher("/pages/user/login_success.jsp").forward(request, response);
        }
    }

    /**
     * 注销功能
     *
     * @param request  请求
     * @param response 响应
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 清除Session信息
        request.getSession().invalidate();
        // 重定向回首页
        response.sendRedirect(request.getContextPath());
    }
}
